import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

public class ReadXML {

    @Test
    public void test() throws DocumentException {
        //1.创建解析器对象
        SAXReader sr = new SAXReader();
        //2.获取文档对象
        Document document = sr.read("C:\\21.7.31\\src\\Book.xml");

        //3.获取指定 id值的节点的所有内容 (id = 01)
        Node att = document.selectSingleNode("/books/book[@id='01']/attribute::id");
        System.out.println("图书id = " + att.getText());
        att = document.selectSingleNode("/books/book[@id='01']/attribute::出版社");
        System.out.println("出版社 = " + att.getText());

        List<Node> book1 = document.selectNodes("/books/book[@id='01']//*");
        for (Node node : book1) {
            System.out.println(node.getName()+" = " + node.getText());
        }
        System.out.println("=====================================================");

        //3. 获取指定 id值的节点的所有内容 (id = 02)
        att = document.selectSingleNode("/books/book[@id='02']/attribute::id");
        System.out.println("图书id = " + att.getText());
        att = document.selectSingleNode("/books/book[@id='02']/attribute::出版社");
        System.out.println("出版社 = " + att.getText());

        List<Node> book2 = document.selectNodes("/books/book[@id='02']//*");
        for (Node node : book2) {
            System.out.println(node.getName()+" = " + node.getText());
        }
        System.out.println("=====================================================");

        //3. 获取指定 id值的节点的所有内容 (id = 03)
        att = document.selectSingleNode("/books/book[@id='03']/attribute::id");
        System.out.println("图书id = " + att.getText());
        att = document.selectSingleNode("/books/book[@id='03']/attribute::出版社");
        System.out.println("出版社 = " + att.getText());

        List<Node> book3 = document.selectNodes("/books/book[@id='03']//*");
        for (Node node : book3) {
            System.out.println(node.getName()+" = " + node.getText());
        }
    }
}
